import { useState } from 'react';
import { Link } from 'react-scroll';

import { ratingApi } from '@/entities/rating';
import { CourseDto } from '@/shared/interfaces/generated';
import { declension, getImageUrl, validateYoutubeLink } from '@/shared/lib';
import { Button, RatingTag, Slider, Title } from '@/shared/ui';
import { ModalPage } from '@/widgets/ModalPage';
import cn from 'classnames';
import Image from 'next/image';
import { useWindowSize } from 'usehooks-ts';

import cs from './AboutCourse.module.scss';

export const AboutCourse = ({ course }: { course: CourseDto }) => {
  const { width } = useWindowSize();
  const { data: ratings } = ratingApi.useGetProductRatingsQuery(String(course?.product?.id));
  const reviews = ratings?.ratings || [];
  const [index, setIndex] = useState<number>(0);
  const [isOpen, setIsOpen] = useState(false);
  const handleOpen = (index?: number) => {
    if (width > 1024) {
      return;
    }
    if (index !== undefined) {
      setIndex(index);
    }
    setIsOpen(() => true);
  };
  const images = [...course?.product.media]
    .filter(({ file }) => file)
    .sort((a, b) => a.order - b.order)
    .slice(0, 2);
  return (
    <>
      <div className={cs.about}>
        <div className={cs.info}>
          <div>
            {course?.product.title && (
              <Title className={cs.main_title} tag="h1">
                {course?.product.title}
              </Title>
            )}
            <p className={cs.course_type}>{course?.format?.title || 'Гайд'}</p>
          </div>
          {!!course?.product.averageRate && !!reviews && (
            <div className={cs.rating}>
              <RatingTag
                isCard={width > 1024}
                value={course?.product.averageRate as unknown as number}
                variant="secondary"
              />
              <Link className={cn(cs.link)} duration={100} offset={-120} smooth to="reviews">
                {reviews?.length} {declension(reviews?.length, ['отзыв', 'отзыва', 'отзывов'])}
              </Link>
            </div>
          )}
          {!!course?.product.description && (
            <div className={cs.moreBlock}>
              <div className={cs.descriptionBasic} dangerouslySetInnerHTML={{ __html: course?.product.description }} />
            </div>
          )}
          {!!validateYoutubeLink(course?.videoLink) && (
            <div className={cs.video}>
              <iframe
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
                data-testid="youtube-player"
                loading="lazy"
                src={validateYoutubeLink(course?.videoLink) as string}
                title="Embedded youtube"
              />
            </div>
          )}
        </div>
        {!!images?.length && (
          <div className={cs.book}>
            {images.map((image, index) => (
              <Button
                className={cs.book_image}
                data-testid={`button-open_image_${index}`}
                key={image.id}
                onClick={() => handleOpen(index)}
              >
                <Image
                  alt="page"
                  fill
                  priority
                  sizes="100vw, (max-width: 768px) 50vw, (max-width: 1024px) 33vw, (max-width: 1366px) 25vw, 20vw"
                  src={getImageUrl(image.file)}
                />
              </Button>
            ))}
          </div>
        )}
      </div>
      <ModalPage handleClose={() => setIsOpen(false)} isMobile isOpen={isOpen}>
        <Slider
          className={cs.slider}
          initialSlideIndex={index}
          slides={images.map((image, index) => ({
            id: index,
            data: (
              <div className={cs.book_image_slide} key={image.id}>
                <Image
                  alt="page"
                  fill
                  priority
                  sizes="100vw, (max-width: 768px) 50vw, (max-width: 1024px) 33vw, (max-width: 1366px) 25vw, 20vw"
                  src={getImageUrl(image.file)}
                />
              </div>
            ),
          }))}
        />
      </ModalPage>
    </>
  );
};
